local plugins = require "plugins"
local data_dir = require("global").data_dir
local vim_config_dir = require("global").vim_config_dir
local plugin_loader = {}

function plugin_loader:load(configurations)
  return self.packer.startup(function(use)
    for _, plugin in ipairs(configurations) do
      use(plugin)
    end
  end)
end

function plugin_loader:init()
  self.packer = require("packer")
  local util = require "packer.util"

  self.packer.init {
    package_root = data_dir.."/pack",
    compile_path = vim_config_dir..'/plugin/packer_compiled.lua',
    git = { clone_timeout = 300 },
    display = {
      open_fn = function()
        return util.float { border = 'rounded' }
      end
    }
  }
  return self
end

function plugin_loader:packer()
  local install_path = data_dir..'/pack/packer/start/packer.nvim'
  if vim.fn.empty(vim.fn.glob(install_path)) > 0 then
    vim.fn.system {"git", "clone", "https://github.com/wbthomason/packer.nvim", install_path}
    vim.cmd "packadd packer.nvim"
    plugin_loader:init()
    plugin_loader:load(plugins)
    self.packer.install();
  else
    plugin_loader:init()
    plugin_loader:load(plugins)
  end
end

return {
  init = function ()
    plugin_loader:packer()
  end
}
